import logging

from entity.database.sqlite import Classes, Class_user
from entity.schema.class_schema import ClassesOut, ClassesCreate
from exception.custom_exception import CustomErrorThrowException


async def create_classes_to_core(name: str):
    """
    创建课程到核心系统
    """
    role=await Classes.create(name=name)
    return role

async def get_classes_by_id(classes_id: int):
    """
    通过id获取课程
    """

    classes = await Classes.get_or_none(id=classes_id)
    if not classes:
        logging.error("课程不存在")
        raise CustomErrorThrowException(status_code=501, message="课程不存在")
    new_classes=ClassesOut.from_orm(classes)
    return new_classes



async def update_classes_by_id(classes_id: int, classes:ClassesCreate):
    """
    更新课程到核心系统
    """
    classes_info = await Classes.get_or_none(id=classes_id)
    if not classes_info:
        logging.error("课程不存在")
        raise CustomErrorThrowException(status_code=501, message="课程不存在")
    classes_info.name = classes.name
    await classes_info.save()
    return classes_info

async def delete_classes_by_id(classes_id: int):
    """
    删除课程
    """
    classes_info = await Classes.get_or_none(id=classes_id)
    if not classes_info:
        logging.error("课程不存在")
        raise CustomErrorThrowException(status_code=501, message="课程不存在")
    await classes_info.delete()
    return None


async def count_classes_by_id(classes_id: int):
    """
    统计课程数量
    """
    count = await Class_user.filter(class_id=classes_id).count()
    return count

async def add_count_add(class_id: int,user_id: int):
    """
    增加课程数量
    """
    class_user=await Class_user.create(class_id=class_id,user_id=user_id)
    return class_user